#include "model.h"
#include <QDebug>
#include <QString>
#include <QSqlQuery>
#include <QStringList>
#include <QSqlError>

Model::Model(QObject *parent, QSqlDatabase db) :
        QSqlTableModel(parent, db) {

    createTableIfNeeded();
    setEditStrategy(QSqlTableModel::OnRowChange);
    setTable(MODEL_TABEL_NAME);
    if (!select()) {
        qDebug() << this->lastError();
    }
}
Model::~Model() {
    if (!submitAll()) {
        qDebug() << lastError();
    }
}

Qt::ItemFlags Model::flags ( const QModelIndex & index ) const {
    Qt::ItemFlags flags = this->QAbstractItemModel::flags(index);
    if (index.column() == PRIORITY) {
        return  flags | Qt::ItemIsEditable;
    } else {
        return flags;
    }
}
const QList<Task> &Model::tasks() const {
    return data_;
}

void Model::add(Task task) {
    int row = rowCount();
    if (!insertRow(row)) {
        qDebug() << "Error";
    }
    setData(index(row, URL), task.url);
    setData(index(row, PATH), task.path);
    setData(index(row, PROGRESS), task.progress);
    setData(index(row, PRIORITY), task.priority);
    setData(index(row, STATE), task.state);
    submitAll();
}

int Model::state(int row) const {
    return data(index(row, STATE)).toInt();
}

int Model::priority(int row) const {
    return data(index(row, PRIORITY)).toInt();
}

QUrl Model::url(int row) const {
    return data(index(row, URL)).toUrl();
}

QString Model::path(int row) const {
    return data(index(row, PATH)).toString();
}

void Model::createTableIfNeeded() {
    //QSqlQuery q(database());
    //q.exec(QString("DELETE FROM %1").arg(MODEL_TABEL_NAME));

    QString sql_query = QString("CREATE TABLE %1 ("
                                "url varchar(256), "
                                "path varchar(256), "
                                "progress int, "
                                "priority int, "
                                "finished int)"
                        ).arg(MODEL_TABEL_NAME);

    if (!database().tables().contains(MODEL_TABEL_NAME)) {
        qDebug() << "Creating table";
        QSqlQuery query(database());
        if (!query.exec(sql_query)) {
            qDebug() << query.lastError().text();
        }
    }
}
